package com.wewins.fota.aop;

import com.wewins.fota.sys.service.StatisticService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
@Order(1)
public class ApiStatisticHandler {
    private final StatisticService service;

    public ApiStatisticHandler(StatisticService service) {
        this.service = service;
    }

    @Pointcut("execution(* com.wewins.fota.controller.PublicServeController.checkStatus(*, *))")
    public void statApi() {
    }

    @Pointcut("execution(* com.wewins.fota.service.FotaLogService.*(..))")
    public void statDb() {
    }

    @Pointcut("statApi() || statDb()")
    public void stat() {

    }

    @Around(value = "stat()")
    public Object aroundPoint(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed;
        long start = System.currentTimeMillis();
        try {
            proceed = joinPoint.proceed();
        } finally {
            String costTime = String.valueOf(System.currentTimeMillis() - start);
            Signature signature = joinPoint.getSignature();
            String typeName = signature.getDeclaringTypeName() + "#" + signature.getName();
            service.stat(typeName, costTime);
        }
        return proceed;
    }
}
